const {exec} = require('../db/mysql')
const {SuccessModel,ErrorModel}=require('../model/resModel')

 //获取列表数据
 /* 
1=1:因为下面有判断语句，不写1=1会发生拼接报错，
select * from blogs where 1=1 + `order by createtime desc`
因为author和keyword的值不确定有没有
*/
const getList = (author,keyword) => {
    let sql = `select * from blogs where 1=1 `
    if(author){
        sql += `and author='${author}' `
    }
    if(keyword){
        sql += `and title like '%${keyword}%' `
    }
    const result = exec(sql).then((listData) => {
        return new SuccessModel(listData)
    })
    return result
}
//获取博客详情
const getDelatil = (id) => {
    const sql = `select * from blogs where id='${id}'`
    return exec(sql).then(rows => {
        return rows
    })
}
//新建博客
const newBlog=(blogData = {}) => {
    const title = blogData.title
    const author = blogData.author
    const content = blogData.content
    const createtime = Date.now()
    const sql = `insert into blogs (title, content, author, createtime) value ('${ title }','${ content }','${ author }','${ createtime }')`
    return exec(sql).then(insertData => {
        return {
            id:insertData.insertId
        }
    })
}
//更新博客
const updateBlog = (id,blogData = {})=>{
    const title = blogData.title
    const content = blogData.content
    const sql = `update blogs set title='${ title }',content='${ content }' where id='${ id }'`
    return exec(sql).then(updateData => {
        if(updateData.affectedRows > 0){
            return true
        }
        return false
    })
}
//删除博客
const delBlog = (id,author) => {
    const sql = `delete from blogs where id='${ id }' or author='${ author }'` 
    return exec(sql).then(deleteData => {
        if(deleteData.affectedRows > 0){
            return true
        }
        return false
    })
}

module.exports = {
    getList,
    getDelatil,
    newBlog,
    updateBlog,
    delBlog
}